const app = getApp();

Page({
  data: {
    InputBottom: 0,
    toUserId:'',
    msgList:'',
    message:''
  },
  InputFocus(e) {
    //console.log("InputFocus",e)
    this.setData({
      InputBottom: e.detail.height
    })
  },
  InputBlur(e) {
    //console.log("InputBlur",e)
    this.setData({
      InputBottom: 0,
      message:e.detail.value
    })
  },

   /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
        toUserId:options.toUserId,
    })

    this.setData({
        msgList: app.cache.get('chatRecord-'+this.data.toUserId)
    })


    if(this.data.msgList == '' || this.data.msgList == null || this.data.msgList == undefined){
        this.setData({
            msgList: [{'system':true,'message':{'msg':'快和Ta聊天吧！'}}]
        })
    }

    console.log("toUserId:",this.data.toUserId)
    console.log("msgList",this.data.msgList)

    if(this.data.toUserId == '' || this.data.toUserId == undefined){
        app.showToastFail('toUserId不能为空！')
        return;
    }

    app.checkLoginStatus.checkSession();

    //this.startWebSocket();

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    console.log(app.cache.get('loginUser'))
    const socketTask = new Promise((resolve, reject) => {
        const socketHandler = swan.connectSocket({
            url: `wss://www.ecollege.top/wss/chat/${app.cache.get('loginUser').id}`,
            success: res => {
                console.log('连接WebSocket：', res);
            },
            fail: err => {
                reject(err);
                console.log('连接WebSocket失败', err);
            }
        });

        socketHandler.onOpen(function () {
            console.log('连接WebSocket成功...' );
            resolve(socketHandler);
        });

        socketHandler.onMessage((res) => {
            console.log("收到消息：",res.data);
            let entity = JSON.parse(res.data);
            entity.isSelf = false;
            this.data.msgList.push(entity)
            this.setData({
                msgList:this.data.msgList
            })
            console.log(this.data.msgList)
        });

        socketHandler.onClose(res => {
            console.log('关闭WebSocket', res);
        });

    });
    this.socketTask = socketTask;

  },

  socketTaskSend() {

    let entity = {
        'fromUserId':app.cache.get('loginUser').id,
        'toUserId':this.data.toUserId,
        'message':{'msg':this.data.message}
    }

    var record =  {
        'fromUserId':app.cache.get('loginUser').id,
        'toUserId':this.data.toUserId,
        'message':{'msg':this.data.message},
        'system':false,
        'isSelf':true,
        'fromUser':app.cache.get('loginUser')
    }

    //msgList中添加记录
    this.data.msgList.push(record);
    this.setData({
        msgList:this.data.msgList
    })

    this.socketTask.then(socketHandler => {
        socketHandler.send({
            data: JSON.stringify(entity),
            success: res => {
                console.log('WebSocket发送数据成功', res);
            },
            fail: err => {
                swan.showModal({
                    title: '发送数据失败',
                    content: JSON.stringify(err)
                });
                console.log('WebSocket发送数据失败', err);
            }
        });
    });
  },

  onHide:function(){
     //消息存入缓存
     app.cache.put('chatRecord-'+this.data.toUserId,this.data.msgList,24*60*60*360)
     console.log("onHide关闭连接")
     swan.closeSocket();
  },
  //
  onUnload: function(){
    //消息存入缓存
    app.cache.put('chatRecord-'+this.data.toUserId,this.data.msgList,24*60*60*360)
    console.log("onUnload关闭连接")
    swan.closeSocket();
  },


  /**
   * 获取聚焦
   */
  focus: function (e) {
    keyHeight = e.detail.height;
    this.setData({
      scrollHeight: (windowHeight - keyHeight) + 'px'
    });
    this.setData({
      toView: 'msg-' + (msgList.length - 1),
      inputBottom: keyHeight + 'px'
    })
    //计算msg高度
    // calScrollHeight(this, keyHeight);
  },

  //失去聚焦(软键盘消失)
  blur: function (e) {
    this.setData({
      scrollHeight: '100vh',
      inputBottom: 0
    })
    this.setData({
      toView: 'msg-' + (msgList.length - 1)
    })

  },

  /**
   * 发送点击监听
   */
  sendClick: function (e) {
    console.log(e)
    msgList.push({
      speaker: 'customer',
      contentType: 'text',
      content: e.detail.value
    })
    this.setData({
      msgList,
      inputVal: e.detail.value
    });

    // console.log(this.data.inputVal)
    sendMessage(this);
  },

  /**
   * 退回上一页
   */
  toBackClick: function () {
    swan.navigateBack({})
  },
  toProfess(){
    swan.navigateTo({
      url: `/packageC/pages/sendProfessContent/sendProfessContent?toUserId=${this.data.toUserId}`
    });
  },

})